var tools = require("../../pros_modules/tools");
var resources = require("./resources.js");
var users = new Object(null);

//用户登录系统
users.dologin = function (req, res, next) {
    if (req.data.username && req.data.password) {
        db.models.user.findOne({
            where: {
                username: req.data.username,
                password: tools.md5(req.data.password)
            },
            include: {model: db.models.userInfo, as: "userInfoObj"}
        }).then(function (datas) {
            if (datas) {
                datas.password = undefined;//登录后去除密码的返回内容
                req.session.LOGIN_USER = datas;//将用户信息保存如session中
                res.restfulsuc(datas);//向客户端输出用户信息内容
                return;
            } else {
                res.restful(CODE.USER_NOT_EXIST);//用户名和密码不匹配
                return;
            }
        });
    } else {
        res.restful(CODE.LOGIN_NP_NULL);//用户名或密码不能为空
        return;
    }
}
//获取当前登录的用户信息
users.getLoginUser = function (req, res, next) {
    res.restfulsuc(req.session.LOGIN_USER);
}
//用户登出
users.doLogout = function (req, res, next) {
    req.session.LOGIN_USER = undefined;//移除session会话中的登录用户
    req.session.destroy();
    res.restfulsuc();
}
//添加新用户
users.doAdd = function (req, res, next) {
    if (req.data)
        db.transaction({autocommit: true}, function (t) {
            return db.models.user.create({
                username: req.data.username,
                password: tools.md5(req.data.password),
                email: req.data.email,
                mobilePhone: req.data.mobilePhone,
                qq: req.data.qq
            }, {transaction: t}).then(function (user) {
                return db.models.userInfo.create({
                    userId: user.id,
                    gengder: '1'
                }, {transaction: t}).then(function (userinfo) {
                });
            });
        }).then(function (t) {
            res.restfulsuc();
            console.log("doAdd successful");
        }).catch(function (e) {
            res.restfulfai();
            console.log(e);
        });
}
//用去当前用户的菜单资源
users.getUserResources = function (req, res, next) {
    var loginUser = req.session.LOGIN_USER;
    //判断是否为超级管理员
    if (loginUser.isAdmin === '1') {//当用户是超级管理员则加载所有的菜单选项
        return resources.loadResourcesTree(req, res, next);
    } else {//非超级管理员需要通过两种方式获取菜单选项 1.通过角色关联查询菜单选项，2.通过用户本身查询出菜单选项
        //1. 通过角色关联查询出菜单选项
        var user_role_resources = undefined;
        var user_resources = undefined;
        var promise = new Promise(function (resolve, reject) {
            db.models.userForRole.findAll({
                    where: {userId: loginUser.id},
                    include: [{
                        model: db.models.role,
                        as: "roleObj",
                        include: {
                            model: db.models.roleForResources, as: "roleForResourcesObj",
                            include: {model: db.models.resources, as: "resourcesObj"}
                        }
                    }],
                    order: "resSort asc"
                }
            ).then(function (userForRoles) {
                    if (userForRoles) {
                        user_role_resources = {};
                        userForRoles.forEach(function (userRole) {
                            userRole.roleObj.roleForResourcesObj.forEach(function (roleForResource) {
                                user_role_resources[roleForResource.resourcesObj.resCode] = roleForResource.resourcesObj;
                            });
                        });
                        resolve();
                    }
                    else
                        reject();
                });
        });
        //2.通过用户本身查询出菜单选项
        promise.then(function () {
                return db.models.userForResources.findAll({
                    where: {userId: loginUser.id},
                    include: {
                        model: db.models.resources, as: "resourcesObj"
                    }
                }).then(function (userResources) {
                    if (userResources) {
                        user_resources = {};
                        userResources.forEach(function (userRes) {
                            user_resources[userRes.resourcesObj.resCode] = userRes.resourcesObj;
                        });
                    }
                    return user_resources;
                });
            }
        ).then(function () {//3.合并数据选项
                var map_resources = user_resources || user_role_resources;
                if (map_resources === user_resources && user_role_resources) {
                    for (var k in user_role_resources) {
                        var res = user_role_resources[k];
                        map_resources[res.resCode] = res;
                    }
                }
                var resources = [];
                for (var k in map_resources) {
                    resources.push(map_resources[k]);
                }
                return resources;
            }).then(function (resources) {//4.将数据项装换为树形结构
                var root_ = {tabid: ''};
                if (resources) {
                    var initTree = function (root) {
                        resources.forEach(function (item) {
                            if (item.resParentCode === root.tabid) {
                                if (!root.childrens)root.childrens = new Array();
                                root.childrens.push(i = {
                                    tabid: item.resCode,
                                    icon: item.resIcon,
                                    lable: item.resName,
                                    href: item.resHref,
                                    isClose: item.isClose,
                                    initOpen: item.initOpen,
                                    type: item.resType
                                });
                                initTree(i);
                            }
                        });
                    };
                    initTree(root_);
                }
                res.restfulsuc(root_.childrens);
            });
    }
}
//设置个人信息
users.setProfile = function (req, res, next) {
    for(var filename in req.files){
        console.log(req.files[filename]);
    }
    res.restfulsuc();
}

module.exports = users;